<?php

namespace Plugins\IMApi\Service;

use Plugins\IMApi\WebSocketMessageHandlerInterface;
use Psr\SimpleCache\InvalidArgumentException;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

class MessageService implements WebSocketMessageHandlerInterface
{

    /**
     * @param Server $server
     * @param Frame $frame
     * @param SenderService $sender
     * @param BindService $bindService
     * @throws InvalidArgumentException
     */
    public function onMessage(Server $server, Frame $frame, SenderService $sender, BindService $bindService): void
    {
        $messageAnalysis = $this->messageAnalysis($frame->data);
        if (!$messageAnalysis) {
            $sender->sendToFd($frame->fd, 'e()请输入正确的消息格式');
            return;
        }

        switch ($messageAnalysis['type']) {
            // 发送消息
            case 's':
                match ($messageAnalysis['tag']) {
                    'fd' => $sender->sendToFd($messageAnalysis['id'], $messageAnalysis['message']),
                    'room' => $sender->sendToRoom($messageAnalysis['id'], $messageAnalysis['message']),
                    'user' => $sender->sendToUserId($messageAnalysis['id'], $messageAnalysis['message']),
                };
                break;
            // 处理消息，加入房间，退出房间
            case 'h':
                switch ($messageAnalysis['handleType']){
                    case '^':
                        $bindService->unBindUserRoom($messageAnalysis['handleInfo']['user'], $messageAnalysis['handleInfo']['room']);
                        $sender->sendToRoom($messageAnalysis['handleInfo']['room'], "用户[{$messageAnalysis['handleInfo']['user']}]已退出群聊", [$messageAnalysis['handleInfo']['user']]);
                        $sender->sendToUserId($messageAnalysis['handleInfo']['user'], '已退出群聊');
                        break;
                    case '&':
                        $bindService->bindUserRoom($messageAnalysis['handleInfo']['user'], $messageAnalysis['handleInfo']['room']);
                        $sender->sendToRoom($messageAnalysis['handleInfo']['room'], "用户[{$messageAnalysis['handleInfo']['user']}]已加入群聊", [$messageAnalysis['handleInfo']['user']]);
                        $sender->sendToUserId($messageAnalysis['handleInfo']['user'], '已加入群聊');
                }
        }
    }


    private function messageAnalysis(string $message): array
    {
        preg_match('/^(s|h)\(((user|room|\d|fd|=|\^|&)+)\)(.*)?$/s', $message, $match);

        if (empty($match)) {
            return [];
        }

        $message = $match[4];
        $type = $match[1];
        $tag = '';
        $id  = 0;
        $handleInfo  = [];
        $handleType  = '';
        if ($type === 's'){
            [$tag, $id] = explode('=', $match[2]);
        }else{
            if(str_contains($match[2], '^')){
                $handleType = '^';
                $handleInfo = array_merge(...array_map(function ($group) {
                    [$tag, $id] = explode('=', $group);
                    return [$tag => $id];
                }, explode('^', $match[2])));
            }else{
                $handleType = '&';
                $handleInfo = array_merge(...array_map(function ($group) {
                    [$tag, $id] = explode('=', $group);
                    return [$tag => $id];
                }, explode('&', $match[2])));
            }
        }

        return [
            'type' => $type,
            'tag'  => $tag,
            'id'   => $id,
            'handleInfo' => $handleInfo,
            'handleType' => $handleType,
            'message' => $message,
        ];
    }
}